<template>
    <app-layout title="购物车">
        <view class="cart-tips">
            <widget-tips text="为什么会拆成多个订单?根据师傅服务能力与服务类型进行订单拆分" />
        </view>
        <view class="cart-container">
            <block v-if="list.length > 0">
                <view class="cart-group" v-for="(item, index) in list" :key="index">
                    <view class="group-title limit-line clamp-1" @click="checkGroup(index)">
                        <view class="group-checkbox">
                            <widget-check-box :size="50" :checked="item.checked" />
                        </view>
                        <view class="title">
                            <text>{{ item.name }}</text>
                        </view>
                    </view>
                    <view class="group-items">
                        <view class="cart-item" v-for="(v, i) in item.list" :key="i" @longpress="deleteCart(index, i)">
                            <view class="item-checkbox" @click="checkItem(index, i)">
                                <widget-check-box :size="50" :checked="v.checked" />
                            </view>
                            <view class="item-box">
                                <service-preview-item :data="v" />
                                <widget-count-modify
                                    class="component-add"
                                    min="1"
                                    :init="v.number"
                                    @change="changeNumber($event, { parentIndex: index, itemIndex: i })"
                                />
                            </view>
                        </view>
                    </view>
                    <view class="bottom-btn-box">
                        <view class="total-price">
                            <text class="text">合计：</text>
                            <text class="price">¥ {{ utils.formatNumber(item.total, 2) }}</text>
                        </view>
                        <view class="button-group">
                            <view v-show="item.canUse" class="button del" @click="deleteCheckedCart(index)">
                                <text>删除</text>
                            </view>
                            <view class="button normal" :class="{ active: item.canUse }" @click="createOrder(index)">
                                <text>去下单</text>
                            </view>
                        </view>
                    </view>
                </view>
            </block>
            <block v-else>
                <view class="empty-data">
                    购物车为空，请先去<text class="choose-service" @click="utils.toPage('/pages/service/cate', {}, 'switch')">
                        选择服务
                    </text>
                </view>
            </block>
        </view>
    </app-layout>
</template>

<script>
import AppLayout from "@/components/layout/layout";
import WidgetTips from "@/components/widgets/tips";
import WidgetCheckBox from "@/components/widgets/checkbox";
import WidgetCountModify from "@/components/widgets/count-modify";
import ServicePreviewItem from "@/components/service/preview-item";
import { mapState } from "vuex";
export default {
    name: "order-cart",
    data() {
        return {
            utils: this.$utils,
            list: [],
        };
    },
    components: {
        AppLayout,
        WidgetTips,
        WidgetCheckBox,
        WidgetCountModify,
        ServicePreviewItem,
    },
    computed: {
        ...mapState({
            cart: (state) => state.cart.cart,
        }),
    },
    onLoad() {
        this.initPage();
    },
    onShow() {},
    onReady() {},
    onReachBottom() {},
    onPullDownRefresh() {},
    onShareTimeline() {},
    onShareAppMessage() {},
    methods: {
        /**
         * 初始化页面
         */
        async initPage() {
            await this.$store.dispatch("cart/update");
            this.list = [];
            this.cart.list.forEach((item) => {
                let goods = [];
                item.good.forEach((v) => {
                    goods.push({
                        id: v.gid,
                        name: v.title,
                        times: v.post_hits,
                        cover: v.thumbnail,
                        price: v.money,
                        number: v.number,
                        checked: false,
                    });
                });
                this.list.push({
                    name: item.cate,
                    total: 0,
                    list: goods,
                    checked: false,
                    canUse: false,
                });
            });
        },
        /**
         * 选中组
         */
        checkGroup(parentIndex) {
            let currentItem = this.list[parentIndex];
            let currentState = !currentItem.checked;
            currentItem.list.forEach((item, itemIndex) => {
                this.checkItem(parentIndex, itemIndex, currentState);
            });
        },
        /**
         * 选中单项
         */
        checkItem(parentIndex, itemIndex, state) {
            let currentItem = this.list[parentIndex].list[itemIndex];
            let currentState = typeof state === "undefined" ? !currentItem.checked : state;
            if (currentItem.checked != currentState) {
                currentItem.checked = currentState;

                // 判断是否需要选中组
                let allChecked = true,
                    canUse = false;
                this.list[parentIndex].list.forEach((item, index) => {
                    if (!item.checked) {
                        allChecked = false;
                    } else {
                        canUse = true;
                    }
                });
                this.list[parentIndex].checked = allChecked;
                this.list[parentIndex].canUse = canUse;

                this.updateTotal(parentIndex);
            }
        },
        /**
         * 更新总价
         */
        updateTotal(parentIndex) {
            let currentItem = this.list[parentIndex],
                total = 0;
            currentItem.list.forEach((item) => {
                if (item.checked) {
                    total += item.price * item.number;
                }
            });
            currentItem.total = total;
        },
        /**
         * 改变数量
         */
        changeNumber(e, idx) {
            let currentItem = this.list[idx.parentIndex].list[idx.itemIndex];
            if (currentItem.number != e.value) {
                this.$models.cart.change(currentItem.id, e.type).then(() => {
                    this.$store.dispatch("cart/update", true);
                    currentItem.number = e.value;
                    this.updateTotal(idx.parentIndex);
                });
            } else {
                if (e.type == "sub") {
                    this.deleteCart(idx.parentIndex, idx.itemIndex);
                }
            }
        },
        /**
         * 公共删除
         */
        commonDeleteCart(parentIndex, itemIndexes) {
            const that = this;
            uni.showModal({
                title: "确定删除该商品？",
                content: "数据删除后不可恢复，请谨慎操作！",
                async complete(res) {
                    if (!res.confirm) return;
                    let parentItem = that.list[parentIndex];
                    itemIndexes = itemIndexes.sort((a, b) => b - a);
                    for (let i = 0; i < itemIndexes.length; i++) {
                        let currentItem = parentItem.list[itemIndexes[i]];
                        await that.$models.cart.delete(currentItem.id).then(() => {
                            parentItem.list.splice(itemIndexes[i], 1);
                            if (parentItem.list.length > 0) {
                                that.updateTotal(parentIndex);
                            } else {
                                that.list.splice(parentIndex, 1);
                            }
                        });
                    }
                    let hasChecked = false;
                    parentItem.list.forEach((item) => {
                        if (item.checked) {
                            hasChecked = true;
                        }
                    });
                    parentItem.canUse = hasChecked;
                    that.$store.dispatch("cart/update", true);
                },
            });
        },
        /**
         * 删除购物车
         */
        deleteCart(parentIndex, itemIndex) {
            this.commonDeleteCart(parentIndex, [itemIndex]);
        },
        /**
         * 删除选中购物车
         */
        deleteCheckedCart(parentIndex) {
            let currentItem = this.list[parentIndex];
            let indexes = [];
            currentItem.list.forEach((item, itemIndex) => {
                if (item.checked) {
                    indexes.push(itemIndex);
                }
            });
            this.commonDeleteCart(parentIndex, indexes);
        },
        /**
         * 购物车下单
         */
        createOrder(parentIndex) {
            let orderdata = [];
            let currentItem = this.list[parentIndex];
            currentItem.list.forEach((item) => {
                if (item.checked) {
                    orderdata.push({
                        id: item.id,
                        count: item.number,
                    });
                }
            });
            if (orderdata.length > 0) {
                this.$utils.toPage("/pages/order/create?orderData=" + encodeURIComponent(JSON.stringify(orderdata)));
            }
        },
    },
};
</script>

<style lang="less" scoped>
.cart-tips {
    width: 710rpx;
    margin: 0 auto 24rpx auto;
}
.cart-container {
    width: 710rpx;
    margin: 0 auto;
    padding-bottom: 40rpx;
}
.cart-group {
    width: 100%;
    margin-bottom: 22rpx;
    background-color: #ffffff;
}
.cart-group:last-child {
    margin-bottom: 0;
}
.group-title {
    width: 100%;
    box-sizing: border-box;
    padding: 22rpx;
    display: flex;
    align-items: center;
    .title {
        margin-left: 22rpx;
        font-size: 26rpx;
        font-weight: bold;
        color: #000000;
    }
}
.group-items {
    width: 100%;
    .cart-item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 22rpx;
        margin-bottom: 50rpx;
    }
    .item-box {
        position: relative;
        width: 604rpx;
        .component-add {
            position: absolute;
            right: 0;
            bottom: 9rpx;
        }
    }
}
.bottom-btn-box {
    width: 670rpx;
    margin: 0 auto;
    border-top: 2rpx solid #e1e1e1;
    box-sizing: border-box;
    padding: 26rpx 0;
    display: flex;
    justify-content: space-between;
    .total-price {
        .text {
            font-size: 26rpx;
            color: #000000;
        }
        .price {
            font-size: 32rpx;
            color: #ec7655;
        }
    }
    .button-group {
        display: flex;
    }
    .button {
        height: 54rpx;
        line-height: 54rpx;
        text-align: center;
        border-radius: 23rpx;
        font-size: 24rpx;
        box-sizing: border-box;
        margin-left: 20rpx;
    }
    .button.del {
        width: 90rpx;
        color: #666666;
        border: 2rpx solid #e0e0e0;
        line-height: 50rpx;
    }
    .button.normal {
        width: 183rpx;
        color: #ffffff;
        background: linear-gradient(-90deg, #8194f2, #8194f2);
        opacity: 0.7;
    }
    .button.normal.active {
        opacity: 1;
    }
}
.more {
    padding: 50rpx 0;
}
.empty-data {
    width: 100%;
    box-sizing: border-box;
    padding: 100rpx 50rpx;
    text-align: center;
    color: #999999;
    font-size: 28rpx;
    .choose-service {
        color: #8194f2;
        font-weight: bold;
    }
}
</style>